﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Text;

namespace B10.Helpers
{
    public static class UrlHelperExtensions
    {
        static readonly int _maxUrlLength = 160;
        static readonly string Original = "áäąàâãçčćďéěęêğíıĺľłňńóôőöôõŕřšşśąčęėįšųūžöüóőúéáűíàéèêôùëçâĄČĘĖĮŠŲŪŽťúůüűýžźżÁÄĄÀÂÃČĆÇĎÉĚĘÉÊÍĹĽŁŇŃÔÖÓŐÕÖÜÓŐÚÉÁŰÍÁÂÄÈÉÊËÎÏÔÖÙÛÇŘŔŠŞŚŤÚÜÝŽŹŻ";
        static readonly string Stripped = "aaaaaacccdeeeegiilllnnoooooorrsssaceeisuuzouooueauiaeeeouecaACEEISUUZtuuuuyzzzAAAAAACCCDEEEEEILLLNNOOOOOOUOOUEAUIAAAEEEEIIOOUUCRRSSSTUUYZZZ";

        public static string GetValidUrlFromString(this UrlHelper urlHelper, string value)
        {
            if (String.IsNullOrEmpty(value))
                throw new ArgumentNullException("value");
            StringBuilder sb = new StringBuilder();
            bool isInWhiteSpace = false;
            foreach (char c in value)
            {
                if (Char.IsWhiteSpace(c) || !Char.IsLetterOrDigit(c))
                {
                    if (!isInWhiteSpace)
                    {
                        sb.Append('-');
                        isInWhiteSpace = true;
                    }
                    continue;
                }
                int index = Original.IndexOf(c);
                if (index >= 0)
                    sb.Append(Stripped[index]);
                else
                    sb.Append(c);
                isInWhiteSpace = false;
            }
            value = sb.ToString().Trim('-');
            if (!Uri.IsWellFormedUriString(value, UriKind.Relative))
                value = Uri.EscapeUriString(value);


            if (value.Length > _maxUrlLength)
                return value.Substring(0, _maxUrlLength);
            return value;
        }
    }
}
